<?php

namespace mybackend\controllers\mtp;

use common\services\common\MyscrmAuthorizeService;
use common\services\common\MyscrmContractService;
use common\services\common\MyscrmPackageService;
use common\services\common\MyscrmOrganizationService;
use mybackend\controllers\BaseController;
use common\entities\myhtsq\ActionCode;

use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\Response;
use Yii;

/**
 * Site controller
 */
class MyscrmOrganizationController extends BaseController {

    private $_myscrmOrganizationService = null;
    private $_packageService = null;
    private $_contractService = null;
    private $_authorizeService = null;
    private $_request = null;
    public  $enableCsrfValidation = false;
    public $layout = '@app/views/mtp/layouts/main.php';
    private $_show = false;

    public function __construct($id, $module,
                                MyscrmOrganizationService $myscrmOrganizationService,
                                MyscrmPackageService $packageService,
                                MyscrmContractService $contractService,
                                MyscrmAuthorizeService $authorizeService,
                                $config = []) {
        $this->_myscrmOrganizationService = $myscrmOrganizationService;
        $this->_packageService = $packageService;
        $this->_contractService = $contractService;
        $this->_authorizeService = $authorizeService;
        $this->_request = Yii::$app->request;
        parent::__construct($id, $module, $config);
    }
    
    protected function roleAuthRules() {
        return [
            'actions' => ['GetOrgs'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'GetOrgs' => ActionCode::EXP_MANAGE_VIEW,
                    ]
                ]
            ]
        ];
    }

    public function actionIndex(){
        return $this->render("index");
    }

    public function beforeAction($action)
    {
        if($this->_request->request("show", false)){
            $this->_show = true;
        }
        return parent::beforeAction($action);
    }

    /**
     * 得到商户列表
     * @return type|string
     */
    public function actionGetOrgs(){
        $requestData = $this->_request->request();
        $_order = ArrayHelper::getValue($requestData, 'order', "asc");
        if($_order == 'desc'){
            $_order = SORT_DESC;
        }else{
            $_order = SORT_ASC;
        }
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $orgs = $this->_myscrmOrganizationService->getOrganizationListByPage(
                ArrayHelper::getValue($requestData, 'keyword', ''),
                intval(ArrayHelper::getValue($requestData, 'page', 1)),
                intval(ArrayHelper::getValue($requestData, 'pageSize', 10)),
                ArrayHelper::getValue($requestData, 'sort-field', "Id"),
                $order=$_order);
        }catch(\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }
        if($this->_show){
            return $this->render('orgs-list', ['orgs' => $orgs]);
        }else{
            if(!empty($orgs)){
                $response['data'] = $orgs;
            }
            return $this->json($response);
        }
    }

    public function actionAddPackage(){
        $this->_packageService->addPackage($this->_request->post());
    }

    public function actionGetPackages(){
        return $this->json($this->_packageService->getAllPackage('unique_name', SORT_DESC));
    }


    public function actionAddAppToPkg(){
        return $this->json($this->_packageService->addApplicationToPackage($this->_request->post('package_id'), $this->_request->post('application_id')));
    }

    public function actionDelNoUseAppInPkg(){
        return $this->json($this->_packageService->delNoUsePackageApplication());
    }

    public function actionModifyPkgPrice(){
        return $this->json($this->_packageService->modifyPackagePrice($this->_request->post('package_id'),
            $this->_request->post('price'), $this->_request->post('unit')));
    }

    public function actionAppInPkg(){
        return $this->json($this->_packageService->getApplicationInPackage($this->_request->post('package_id')));
    }

    public function actionGetOrgById(){
        return $this->json($this->_myscrmOrganizationService->getOrgById($this->_request->post('id')));
    }

    /**
     * 新增或更改合同
     * @return mixed
     */
    public function actionSaveContract(){

        $post = $this->_request->post();

        if(!array_key_exists('contract_num', $post) || !array_key_exists('party_a', $post) ||
            !array_key_exists('contract_type', $post) || !array_key_exists('begin_on', $post) ||
            !array_key_exists('end_on', $post) || !array_key_exists('organization_id', $post) ||
            !array_key_exists('auth_info', $post)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "参数不能为空"]);
        }

        $contractId = ArrayHelper::getValue($post, 'contract_id');
        $contractNum = ArrayHelper::getValue($post, 'contract_num');
        $partyA = ArrayHelper::getValue($post, 'party_a');
        $contractType = ArrayHelper::getValue($post, 'contract_type');
        $beginOn = ArrayHelper::getValue($post, 'begin_on');
        $endOn = ArrayHelper::getValue($post, 'end_on');
        $organizationId = ArrayHelper::getValue($post, 'organization_id');
        $authInfo = ArrayHelper::getValue($post, 'auth_info');
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $result = $this->_contractService->saveContractAuth([
                'contract_id' => $contractId,
                'contract_num' => $contractNum,
                'party_a' => $partyA,
                'organization_id' => $organizationId,
                'contract_type' => $contractType,
                'begin_on' => $beginOn,
                'end_on' => $endOn,
                'auth_info' => json_decode($authInfo, True),
            ]);
        }catch(\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        if(!empty($result)){
            $response['data'] = 1;
        }else{
            $response['retCode'] = -1;
            $response['retMsg'] = '保存失败';
            $response['result'] = false;
        }
        return $this->json($response);

    }

    public function actionGetContracts(){
        return $this->json($this->_contractService->getContractsByOrgId(ArrayHelper::getValue($this->_request->post(), "organization_id")));
    }

    /**
     * 获取合同列表
     * @return mixed
     */
    public function actionGetContractsList(){
        $requestData = $this->_request->request();
        if(!array_key_exists('orgname', $requestData)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $list = $this->_contractService->getContractsList(ArrayHelper::getValue($requestData, "orgname"));
        }catch(\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        if(!empty($list)){
            $response['data'] = $list;
        }else{
            $response['retCode'] = -1;
            $response['retMsg'] = '获取失败';
            $response['result'] = false;
        }
        if(array_key_exists('show', $requestData)){
            return $this->render('contracts-list', ['list' => $list, 'orgName' => ArrayHelper::getValue($requestData, 'orgname')]);
        }else{
            return $this->json($response);
        }


    }

    /**
     * 作废合同
     */
    public function actionCancelContract(){
        $postData = $this->_request->post();
        if(!array_key_exists('orgname', $postData) || !array_key_exists('contract_id', $postData)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "缺少参数"]);
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];

        try{

            $this->_contractService->cancelContract(ArrayHelper::getValue($postData, 'orgname'), ArrayHelper::getValue($postData, 'contract_id'));
        }catch(\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        return $this->json($response);

    }

    public function actionGetContract(){
        return $this->json($this->_contractService->getContractById(ArrayHelper::getValue($this->_request->post(), "contract_id")));
    }

    public function actionGetAuthorizedAppByCode(){
        return $this->json($this->_authorizeService->getAuthorizedAppByCode(
            ArrayHelper::getValue($this->_request->post(), "orgname"),
            ArrayHelper::getValue($this->_request->post(), "authcode")
            )
        );
    }

    public function actionGetAuthorizedAppsByOrgName(){
        if(ArrayHelper::getValue($this->_request->request(), "show", 0)){
            return $this->render("apps-list", ["apps" => $this->_authorizeService->getAuthorizedAppsByOrgName(
                ArrayHelper::getValue($this->_request->request(), "orgname")
            )]);
        }else{
            return $this->json($this->_authorizeService->getAuthorizedAppsByOrgName(
                ArrayHelper::getValue($this->_request->request(), "orgname")
            ));
        }

    }

    public function actionGetAuthorizedPackagesByOrgName(){
        $reqData = array_merge($this->_request->post(), $this->_request->get());

        return $this->json($this->_authorizeService->getAuthorizedPackagesByOrgName(
                ArrayHelper::getValue($reqData, "orgname")
            ));
    }

    public function actionGetAuthorizedPackagesByOrgNameNoCurl(){
        $reqData = array_merge($this->_request->post(), $this->_request->get());
        return $this->json($this->_authorizeService->getAuthorizedPackagesByOrgNameNoCurl(
            ArrayHelper::getValue($reqData, "orgname")
        ));
    }

    /**
     * 新租户降级
     * @return mixed
     */
    public function actionOrgDegradation(){
        return $this->json(["retCode" => -1, "result" => false, "retMsg" => "功能已取消"]);
    }

    /**
     * 老租户升级
     * @return mixed
     */
    public function actionOrgUpgrade(){
        return '<div style="color:red">功能已取消</div>';

    }

    public function actionGetPackagesByOrg(){
        $requestData = $this->_request->request();

        if(!array_key_exists('orgname', $requestData)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $pkgs = $this->_authorizeService->getAuthorizedInfoByOrgName(
                ArrayHelper::getValue($requestData, 'orgname')
            );
        }catch (\Exception $ex)
        {
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        if(!empty($pkgs)){
            $response['data'] = $pkgs;
        }

        if(array_key_exists('show', $requestData)){
            return $this->render("authorized-packages", ["pkgs" => $pkgs]);
        }else{
            return $this->json($response);
        }

    }

    /**
     * 拿到已授权数
     * @return mixed
     */
    public function actionGetUsedAuthorizeNum(){
        return $this->json($this->_authorizeService->getUsedAuthorizeNum($this->_request->request('orgname')));
    }

    /**
     * 添加合同
     */
    public function actionAddContractForm(){
        $orgId = $this->_myscrmOrganizationService->getOrgId(ArrayHelper::getValue($this->_request->request(), "orgname"));
        $pkgs = $this->_packageService->getAllPackage();
        return $this->render("add-contract-form", ["orgId" => $orgId, 'pkgs' => $pkgs]);
    }

    /**
     * 编辑合同
     */
    public function actionEditContractForm(){
        $orgId = $this->_myscrmOrganizationService->getOrgId(ArrayHelper::getValue($this->_request->request(), "orgname"));
        $contract = $this->_contractService->getContractDetailById(ArrayHelper::getValue($this->_request->request(), "orgname"),
            ArrayHelper::getValue($this->_request->request(), "contract_id"));
        return $this->render("edit-contract-form", ["orgId" => $orgId, 'contract' => $contract]);
    }

    /**
     * 获取合同信息
     */
    public function actionGetContractInfo(){
        $requestData = $this->_request->request();
        if(!array_key_exists('orgname', $requestData)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }
        if(!array_key_exists('contract_id', $requestData)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户合同ID不能为空"]);
        }
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $contract = $this->_contractService->getContractDetailById(ArrayHelper::getValue($this->_request->request(), "orgname"),
                ArrayHelper::getValue($this->_request->request(), "contract_id"));
        }catch(\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }
        $response['data'] = $contract;
        return $this->json($response);
    }

    /**
     * 获取所有的包
     * @return mixed
     */
    public function actionGetAllPackages(){
        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $pkgs = $this->_authorizeService->getAllApplications();
        }catch(\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }
        $response['data'] = $pkgs;
        return $this->json($response);
    }



    public function actionIsBuyZsslc(){
        return $this->json($this->_authorizeService->isBuyZsslc(ArrayHelper::getValue($this->_request->request(), "orgname")));

    }

    /**
     * 更新租户交付信息
     * @return mixed
     */
    public function actionUpdateDeliverInfo(){

        $requestData = $this->_request->request();
        if(!array_key_exists('orgname', $requestData)){
            return $this->json(["retCode" => -1, "result" => false, "retMsg" => "租户企业号不能为空"]);
        }

        $response = ["retCode" => 0, "result" => true, "retMsg" => ""];
        try{
            $this->_myscrmOrganizationService->updateOrganizationDeliverInfo($requestData);
        }catch (\Exception $ex){
            $response['retMsg'] = $ex->getMessage();
            $response['retCode'] = -1;
            $response['result'] = false;
            return $this->json($response);
        }

        return $this->json($response);
    }

    function actionGetContactTotalNum(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getContactTotalNum(ArrayHelper::getValue($reqData, 'orgname'),
            ArrayHelper::getValue($reqData, 'contract_id')));
    }

    function actionGetAuthorizeTotalNum(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizeTotalNum(ArrayHelper::getValue($reqData, 'authorize_id')));
    }

    function actionGetAuthorizedPackageById(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizedPackageById(ArrayHelper::getValue($reqData, 'orgname'),
            ArrayHelper::getValue($reqData, 'package_id')));
    }

    function actionGetAuthorizedPackagesAndContractsByOrgName(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizedPackagesAndContractsByOrgName(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionGetAuthorizePackageAppBrothersAuthorId(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getAuthorizePackageAppBrothersAuthorId(ArrayHelper::getValue($reqData, 'orgname'),
            ArrayHelper::getValue($reqData, 'auth_id')));
    }

    function actionGetOldOrgPackagesByOrgName(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getOldOrgPackagesByOrgName(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionIsMvp810(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->IsMvp810(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionGetPkgPrice(){
        $reqData = $this->_request->request();
        return $this->json($this->_packageService->getPackagePrice(ArrayHelper::getValue($reqData, 'pkg_id')));
    }

    function actionGetPkgPriceByName(){
        $reqData = $this->_request->request();
        return $this->json($this->_packageService->getPackagePriceByName(ArrayHelper::getValue($reqData, 'pkg_name')));
    }

    function actionGetProjectBindAppNum(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getProjectBindAppNum(ArrayHelper::getValue($reqData, 'orgname')));
    }

    function actionGetProjectIds(){
        $reqData = $this->_request->request();
        return $this->json($this->_authorizeService->getProjectIds(ArrayHelper::getValue($reqData, 'orgname')));
    }


}
